package com.hzeport.bgs22emduty.xxljob;


import cn.gov.customs.casp.sdk.h4a.AccreditBeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.OguBeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.entity.DeptInfo;
import cn.gov.customs.casp.sdk.h4a.entity.OrganizationChildren;
import cn.gov.customs.casp.sdk.h4a.entity.UsersInGroups;
import cn.gov.customs.casp.sdk.h4a.entity.UsersInRoles;
import cn.gov.customs.casp.sdk.h4a.enumdefines.*;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.GroupCategory;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetOrganizationChildrenCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetUsersInGroupsCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.OrganizationCategory;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.hash.CityHash;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.hzeport.bgs22emduty.config.MyProxySelector;
import com.hzeport.bgs22emduty.config.SystemConfig;

import com.hzeport.bgs22emduty.dto.DutyScheduleInfoTimeDTO;
import com.hzeport.bgs22emduty.dto.DutyScheduleInfoTimeDetailDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.entity.h4a.SsoDept;
import com.hzeport.bgs22emduty.entity.h4a.SsoPerson;
import com.hzeport.bgs22emduty.entity.hb.Content;
import com.hzeport.bgs22emduty.entity.hb.Subjecta;
import com.hzeport.bgs22emduty.entity.sync.RcsaDepartment;
import com.hzeport.bgs22emduty.entity.sync.TabHzUserinfo;
import com.hzeport.bgs22emduty.entity.sync.TabSmsdept;
import com.hzeport.bgs22emduty.entity.sync.TabWorkuser;
import com.hzeport.bgs22emduty.enums.*;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.mapper.AbiBasePersonInfoMapper;
import com.hzeport.bgs22emduty.outbound.db.mapper.TabWorkuserMapper;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.service.ScreenEmergencyPlanService;
import com.masa.common.core.base.BaseEntity;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.netty.channel.unix.DomainSocketAddress;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.*;
import java.time.*;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;


/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
@Slf4j
@DS("ZSPT")
public class SampleXxlJob {

    private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Resource
    private RcsaDepartmentRepository rcsaDepartmentRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private TabHzUserinfoRepository tabHzUserinfoRepository;
    @Resource
    private TabWorkuserRepository tabWorkuserRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private TabSmsdeptRepository tabSmsdeptRepository;
    @Resource
    private BaseDeptTypeRepository baseDeptTypeRepository;
    @Resource
    private MessageSendUtil messageSendUtil;
    @Resource
    private ParamSmsTemplateRepository paramSmsTemplateRepository;
    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private ParamLeaderRepository paramLeaderRepository;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ParamDutyRepository paramDutyRepository;
    @Resource
    private DutySignInfoRepository dutySignInfoRepository;
    @Resource
    private BaseDeptInfoService baseDeptInfoService;
    @Resource
    private ScreenEmergencyPlanRepository screenEmergencyPlanRepository;
    @Resource
    private SubjectaRepository subjectaRepository;
    @Resource
    private ContentRepository contentRepository;
    @Resource
    private ScreenNoticeRepository screenNoticeRepository;
    @Resource
    private ParamDictionaryRepository paramDictionaryRepository;
    @Resource
    private ScreenSchedulePersonRepository screenSchedulePersonRepository;
    @Resource
    private ScreenDutyMapsRepository screenDutyMapsRepository;
    @Resource
    private ScreenDutyLogRepository screenDutyLogRepository;
    @Resource
    private ScreenDutyMessageRepository screenDutyMessageRepository;
    @Resource
    private ScreenDutyNoticeListRepository screenDutyNoticeListRepository;
    @Resource
    private AbiBasePersonInfoRepository abiBasePersonInfoRepository;
    @Resource
    private DeptCustomRepository deptCustomRepository;
    @Resource
    private ParamSmsPeopleRepository paramSmsPeopleRepository;
    @Resource
    private BaseGroupInfoRepository baseGroupInfoRepository;
    @Resource
    private BaseGroupUserRelationRepository baseGroupUserRelationRepository;



    @XxlJob("getUserInfo")
    public ReturnT<String> getUserInfo(String param) {
        try {
            log.info( "===部门和人员拉取任务开始===" );

            // H4A部门列表获取
            OguBeanReaderHelper helperdept = new OguBeanReaderHelper();
            OrganizationChildren[] ogus = helperdept.getBeanOrganizationChildren(systemConfig.getViewValues(), ViewCategory.ViewCode, systemConfig.getOrgValues(), OrganizationCategory.ORG_ALL_PATH_NAME, ListObjectCategories.Organizations, ObjectStatusCategories.All, 0, "05,06,07,08,99", "", "", 0, "ORG_GUID,PARENT_GUID,ALL_PATH_NAME,GLOBAL_SORT,DISPLAY_NAME,CUSTOMS_CODE,ORG_CLASS,ORG_TYPE,RANK_CODE,RANK_TYPE");
            // H4A部门列表
            List< SsoDept > ssoDeptList = new ArrayList<>();
            // h4a查询部门信息
            if ( ogus != null && ogus.length > 0 ) {
                for ( int i = 0; i < ogus.length; i++ ) {
                    OrganizationChildren organizations = ogus[ i ];
                    String display_name = organizations.getDisplay_name();
                    String org_guid = organizations.getOrg_guid();
                    String parent_guid = organizations.getParent_guid();
                    String all_path_name = organizations.getAll_path_name();
                    String global_sort = organizations.getGlobal_sort();
                    String customs_code = organizations.getCustoms_code();
                    String org_class = organizations.getOrg_class();
                    String org_type = organizations.getOrg_type();
                    String rank_code = organizations.getRank_code();
                    SsoDept ssoDept = new SsoDept();
                    ssoDept.setAllPathName( all_path_name );
                    ssoDept.setCustomsCode( customs_code );
                    ssoDept.setDisplayName( display_name );
                    ssoDept.setGlobalSort( global_sort );
                    ssoDept.setOrgClass( org_class );
                    ssoDept.setOrgGuid( org_guid );
                    ssoDept.setOrgType( org_type );
                    ssoDept.setParentGuid( parent_guid );
                    ssoDept.setRankCode( rank_code );
                    log.info( ssoDept + "" );
                    ssoDeptList.add( ssoDept );
                }
            }

            String notUseDeptString = paramDictionaryRepository.getOne( new LambdaQueryWrapper< ParamDictionary >()
                    .eq( ParamDictionary::getParamCode , "BSYBM" ) , false ).getParamName();
            String CJDeptName = paramDictionaryRepository.getOne( new LambdaQueryWrapper< ParamDictionary >()
                    .eq( ParamDictionary::getParamCode , "CJBM" ) , false ).getParamName();
            String KZWord = paramDictionaryRepository.getOne( new LambdaQueryWrapper< ParamDictionary >()
                    .eq( ParamDictionary::getParamCode , "KZWD" ) , false ).getParamName();

            List< String > notUseDeptNames = Arrays.asList( notUseDeptString.split( "," ) );
            List< String > CJDeptNames = Arrays.asList( CJDeptName.split( "," ) );
            List< String > KZWords = Arrays.asList( KZWord.split( "," ) );
            List< String > CJDeptIds = new ArrayList<>();

            // 将三统一部门和通讯录部门结合起来,保存到我们的数据库
            List<BaseDeptInfo> baseDeptInfos = ssoDeptList.stream().map(i -> {
                BaseDeptInfo baseDeptInfo = new BaseDeptInfo();
                baseDeptInfo.setOrgGuid(i.getOrgGuid());
                RcsaDepartment rcsaDepartment = null;
                baseDeptInfo.setDeptFullName(i.getAllPathName());
                baseDeptInfo.setParentid(i.getParentGuid());
                baseDeptInfo.setGlobalSort(i.getGlobalSort());
                baseDeptInfo.setDeptName(i.getDisplayName());
//                baseDeptInfo.setCustomId(i.getCustomsCode());
                baseDeptInfo.setId(i.getOrgGuid());
                if (ObjectUtils.isEmpty( rcsaDepartment )) {
                    log.info("机构名"+i.getAllPathName()+"未找到");
                }else {
//                    baseDeptInfo.setDeptFullName(rcsaDepartment.getName());
//                    baseDeptInfo.setGlobalSort(rcsaDepartment.getGlobalsort());;
//                    baseDeptInfo.setDeptName(rcsaDepartment.getDepartmentname());
                }
                if ( notUseSSoDept( i , notUseDeptNames ) ) {
                    log.info( "不使用的部门" + baseDeptInfo );
                    baseDeptInfo.setNotUseKJDept( "1" );
                }else {
                    baseDeptInfo.setNotUseKJDept( "0" );
                }
                if ( isCJDept( i , CJDeptNames ) ) {
                    log.info( "处级部门" + baseDeptInfo );
                    CJDeptIds.add( i.getOrgGuid() );
                }
                baseDeptInfo.setCreateBy( "-1" );
                baseDeptInfo.setCreateTime( LocalDateTime.now() );
                baseDeptInfo.setUpdateBy( "-1" );
                baseDeptInfo.setUpdateTime( LocalDateTime.now() );
                baseDeptInfo.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
                return baseDeptInfo;
            } ).filter( i -> i != null ).collect( Collectors.toList() );
            // 用户列表获取
            OguBeanReaderHelper helper = new OguBeanReaderHelper();
            OrganizationChildren[] base_views = helper.getBeanOrganizationChildren(systemConfig.getViewValues(), ViewCategory.ViewCode, systemConfig.getOrgValues(), OrganizationCategory.ORG_ALL_PATH_NAME, ListObjectCategories.Sideline, ObjectStatusCategories.All, 0, "05,06,07,08,99", "", "", 0, "PARENT_GUID,USER_GUID,DEPT_GUID,DISPLAY_NAME,PERSON_ID,GLOBAL_SORT,STATUS,ALL_PATH_NAME,RANK_CODE,RANK_NAME");
            List< SsoPerson > ssoPersonList = new ArrayList<>();
            if ( base_views != null && base_views.length > 0 ) {
                for ( int i = 0; i < base_views.length; i++ ) {
                    OrganizationChildren organizationChildren = base_views[ i ];
                    List< String > userStatusList = Arrays.asList( systemConfig.getSsoUserStatus().split( "," ) );
                    if ( ! userStatusList.contains( organizationChildren.getStatus() ) ) {
                        String all_path_name = organizationChildren.getAll_path_name();
                        String display_name = organizationChildren.getDisplay_name();
                        String global_sort = organizationChildren.getGlobal_sort();
                        String user_guid = organizationChildren.getUser_guid();
                        String rank_code = organizationChildren.getRank_code();
                        String parent_guid = organizationChildren.getParent_guid();
                        String person_id = organizationChildren.getPerson_id();
                        String status = organizationChildren.getStatus();
                        String rankName = organizationChildren.getRank_name();
                        SsoPerson ssoPerson = new SsoPerson();
                        ssoPerson.setAllPathName( all_path_name );
                        ssoPerson.setDeptGuid( parent_guid );
                        ssoPerson.setParentGuid( organizationChildren.getParent_guid() );
                        ssoPerson.setDisplayName( display_name );
                        ssoPerson.setGlobalSort( global_sort );
                        ssoPerson.setPersonId( person_id );
                        ssoPerson.setRankCode( rank_code );
                        ssoPerson.setStatus( Long.valueOf( status ) );
                        ssoPerson.setUserGuid( user_guid );
                        ssoPerson.setRankName( rankName );
                        String notUserPersons = systemConfig.getNotUsePersons();
                        if ( ! StringUtils.isEmpty( notUserPersons ) ) {
                            List< String > array = Arrays.asList( notUserPersons.split( "," ) );
                            if ( ! CollectionUtils.isEmpty( array ) && array.contains( rankName ) ) {
                                log.info( "过滤人员" + ssoPerson + "|" + rankName );
                            }else {
                                ssoPersonList.add( ssoPerson );
                            }
                        }else {
                            ssoPersonList.add( ssoPerson );
                        }
                        log.info( ssoPerson + "|" + rankName );
                    }
                }
            }
            UsersInRoles[] roleUser;
            List< ScreenDutyMaps > allCustomMap = screenDutyMapsRepository.list();
            baseDeptInfos = getDeptCustom( baseDeptInfos , allCustomMap );
            Map<String,String> deptCustomMap=baseDeptInfos.stream().collect(Collectors.toMap(BaseDeptInfo::getId,BaseDeptInfo::getCustomId));
            //将三统一用户和通讯录用户结合起来,保存到我们的数据库
            List< BasePersonInfo > basePersonInfos = ssoPersonList.stream().map( i -> {
                BasePersonInfo basePersonInfo = new BasePersonInfo();
                basePersonInfo.setUserno( i.getPersonId() );
                basePersonInfo.setUsername( i.getDisplayName() );
                basePersonInfo.setDeptId( i.getDeptGuid() );
                if ( i.getDeptGuid() != null && deptCustomMap.get( i.getDeptGuid() ) != null ) {
                    String customId = deptCustomMap.get( i.getDeptGuid() );
                    basePersonInfo.setCustomId( customId );
                }
                basePersonInfo.setCreateBy( "-1" );
                basePersonInfo.setCreateTime( LocalDateTime.now() );
                basePersonInfo.setUpdateBy( "-1" );
                basePersonInfo.setUpdateTime( LocalDateTime.now() );
                basePersonInfo.setRankCode( i.getRankCode() );
                basePersonInfo.setGlobalSort( i.getGlobalSort() );
                basePersonInfo.setRealRackCode( i.getRankCode() );
                basePersonInfo.setUserGuid( i.getUserGuid() );
                basePersonInfo.setParentGuid( i.getParentGuid() );
                basePersonInfo.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
                if ( basePersonInfo.getUserno() == null ) {
                    return null;
                }
                if ( CJDeptIds.contains( basePersonInfo.getDeptId() ) ) {
                    basePersonInfo.setRankCode( "07" );
                }else {
                    if ( KZWords.contains( i.getRankName() ) ) {
                        log.info( "视为科长" + i );
                        basePersonInfo.setRankCode( "09" );
                    }else {
                        log.info( "视为科员" + i );
                        basePersonInfo.setRankCode( "11" );
                    }
                }
                return basePersonInfo;
            } ).filter( i -> i != null ).collect( Collectors.toList() );

            basePersonInfos=basePersonInfos.stream().filter(i->i!=null&&!StringUtils.isEmpty(i.getUserno())).collect(Collectors.toList());
            //进行通讯录
//            basePersonInfos=getPersonAddressMsg(basePersonInfos);
//            baseDeptInfoRepository.remove(new LambdaQueryWrapper<>());
//            baseDeptInfoRepository.saveBatch(baseDeptInfos);
//            basePersonInfoRepository.remove(new LambdaQueryWrapper<>());
//            basePersonInfoRepository.saveBatch(basePersonInfos);
//            abiBasePersonInfoRepository.remove(new LambdaQueryWrapper<>());
//            List<AbiBasePersonInfo> abiBasePersonInfos=basePersonInfos.stream().map(i->{
//                AbiBasePersonInfo abiBasePersonInfo=new AbiBasePersonInfo();
//                BeanUtils.copyProperties(i,abiBasePersonInfo);
//                abiBasePersonInfo.setUsernameFull(abiBasePersonInfo.getUsername()+"("+abiBasePersonInfo.getUserno()+")");
//                return abiBasePersonInfo;
//            }).collect(Collectors.toList());
//            abiBasePersonInfos=abiBasePersonInfos.stream().filter(i->i.getUserno()!=null).filter(distinctByKey(i->i.getUserno())).collect(Collectors.toList());
//            abiBasePersonInfoRepository.saveBatch(abiBasePersonInfos);
            // 拉取数据
            Map< String , BaseDeptInfo > baseDeptInfoPullingMap = baseDeptInfos.stream().collect(
                    Collectors.toMap( BaseDeptInfo::getOrgGuid , baseDeptInfo -> baseDeptInfo  , ( baseDeptInfo1 , baseDeptInfo2)  -> baseDeptInfo1 ) );
            // 表中数据
            Map< String , BaseDeptInfo > baseDeptInfoDataMap = baseDeptInfoRepository.list().stream().collect(
                    Collectors.toMap( BaseDeptInfo::getOrgGuid , baseDeptInfo -> baseDeptInfo  , ( baseDeptInfo1 , baseDeptInfo2)  -> baseDeptInfo1 ) );

            // 部门交集(修改的)
            Set< String > updateDeptKeys = new HashSet<>( baseDeptInfoPullingMap.keySet() );
            updateDeptKeys.retainAll( baseDeptInfoDataMap.keySet() );
            List< BaseDeptInfo > updateBaseDept = new ArrayList<>();
            for ( String updateKey : updateDeptKeys ) {
                BaseDeptInfo baseDeptInfoPulling = baseDeptInfoPullingMap.get( updateKey );
                BaseDeptInfo baseDeptInfoData = baseDeptInfoDataMap.get( updateKey );
                BeanUtils.copyProperties( baseDeptInfoPulling , baseDeptInfoData , "id" ,"createTime");
                updateBaseDept.add( baseDeptInfoData );
            }
            // 表里有 拉的数据没有的 (删除)
            Set< String > deleteDeptKeys = new HashSet<>( baseDeptInfoDataMap.keySet() );
            deleteDeptKeys.removeAll( baseDeptInfoPullingMap.keySet() );
            List< BaseDeptInfo > deleteBaseDept = new ArrayList<>();
            for ( String deleteKey : deleteDeptKeys ) {
                BaseDeptInfo baseDeptInfo = baseDeptInfoDataMap.get( deleteKey );
                deleteBaseDept.add( baseDeptInfo );
            }
            // 拉的数据有的 表里没有 (新增)
            Set< String > insertDeptKeys = new HashSet<>( baseDeptInfoPullingMap.keySet() );
            insertDeptKeys.removeAll( baseDeptInfoDataMap.keySet() );
            List< BaseDeptInfo > insertBaseDept = new ArrayList<>();
            for ( String insertKey : insertDeptKeys ) {
                BaseDeptInfo baseDeptInfo = baseDeptInfoPullingMap.get( insertKey );
                insertBaseDept.add( baseDeptInfo );
            }
            baseDeptInfoRepository.saveBatch( insertBaseDept );
            baseDeptInfoRepository.updateBatchById( updateBaseDept );
            baseDeptInfoRepository.removeByIds( deleteBaseDept.stream().map( BaseEntity::getId ).collect( Collectors.toList()) );

            // 拉取数据
            Map< String , BasePersonInfo > basePerInfoPullingMap = basePersonInfos.stream().collect(
                    Collectors.toMap( BasePersonInfo::getUserno , basePersonInfo -> basePersonInfo  , ( basePersonInfo1 ,basePersonInfo2)  -> basePersonInfo1 ) );
            // 表中数据
            Map< String , BasePersonInfo > basePerInfoDataMap = basePersonInfoRepository.list().stream().collect(
                    Collectors.toMap( BasePersonInfo::getUserno , basePersonInfo -> basePersonInfo  , ( basePersonInfo1 , basePersonInfo2)  -> basePersonInfo1 ) );

            // 人员交集(修改的)
            Set< String > updatePerKeys = new HashSet<>( basePerInfoPullingMap.keySet() );
            updatePerKeys.retainAll( basePerInfoDataMap.keySet() );
            List< BasePersonInfo > updateBasePer = new ArrayList<>();
            for ( String updateKey : updatePerKeys ) {
                BasePersonInfo basePertInfoPulling = basePerInfoPullingMap.get( updateKey );
                BasePersonInfo basePertInfoData = basePerInfoDataMap.get( updateKey );
                BeanUtils.copyProperties( basePertInfoPulling , basePertInfoData , "id" ,"createTime");
                updateBasePer.add( basePertInfoData );
            }
            // 表里有 拉的数据没有的 (删除)
            Set< String > deletePerKeys = new HashSet<>( basePerInfoDataMap.keySet() );
            deletePerKeys.removeAll( basePerInfoPullingMap.keySet() );
            List< BasePersonInfo > deleteBasePer = new ArrayList<>();
            for ( String deleteKey : deletePerKeys ) {
                BasePersonInfo baseDeptInfo = basePerInfoDataMap.get( deleteKey );
                deleteBasePer.add( baseDeptInfo );
            }
            // 表里没有 拉的数据有的 (新增)
            Set< String > insertPerKeys = new HashSet<>( basePerInfoPullingMap.keySet() );
            insertPerKeys.removeAll( basePerInfoDataMap.keySet() );
            List< BasePersonInfo > insertBasePer = new ArrayList<>();
            for ( String insertKey : insertPerKeys ) {
                BasePersonInfo baseDeptInfo = basePerInfoPullingMap.get( insertKey );
                insertBasePer.add( baseDeptInfo );
            }
            basePersonInfoRepository.saveBatch( insertBasePer );
            if(CollectionUtil.isNotEmpty(updateBasePer)) {
                basePersonInfoRepository.updateBatchById(updateBasePer);
            }
            if(CollectionUtil.isNotEmpty(deleteBasePer)) {
                basePersonInfoRepository.removeByIds(deleteBasePer.stream().map(BaseEntity::getId).collect(Collectors.toList()));
            }


            baseDeptInfoRepository.remoteNotUseData();
            basePersonInfoRepository.remoteNotUseData();
            log.info("数据拉取完成");
        } catch ( Exception e ) {
            log.error( "定时获取部门数据任务出现执行异常" , e );
        }
        return ReturnT.SUCCESS;
    }


    @XxlJob("getPhone")
//    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> getPhone(String param) {
        try {
            Integer count=basePersonInfoRepository.count();
            Integer index=0;
            Integer page=0;
            Integer value=systemConfig.getPhoneBatchValue();
            if (value==null){
                value=5000;
            }
            while (index+value<count){
                page++;
                index+=value;
                log.info("开始进行第"+page+"页的拉取");
                List<BasePersonInfo>  basePersonInfos=basePersonInfoRepository.page(new Page<>(page,value)).getRecords();
                basePersonInfos=getPhones(basePersonInfos);
                basePersonInfoRepository.updateBatchById(basePersonInfos);
            }
            if (!Integer.valueOf(index+value).equals(count)){
                page++;
                log.info("开始进行第"+page+"页的拉取");
                List<BasePersonInfo> basePersonInfos=basePersonInfoRepository.page(new Page<>(page,value)).getRecords();
                basePersonInfos=getPhones(basePersonInfos);
                basePersonInfoRepository.updateBatchById(basePersonInfos);
            }
        } catch (Exception e) {
            log.error("定时获取部门数据任务出现执行异常", e);
        }
        return ReturnT.SUCCESS;
    }


    private List<BasePersonInfo> getPhones(List<BasePersonInfo> basePersonInfos) throws Exception{
        if (CollectionUtils.isEmpty(basePersonInfos)){
            return basePersonInfos;
        }
        List<BasePersonInfo> resultList=new ArrayList<>();
        ProxySelector proxySelector=new MyProxySelector();
        List<Proxy> proxies=proxySelector.select(new URI(systemConfig.getAddressPhoneUrl()));
        RestTemplate restTemplate;
        if (!CollectionUtils.isEmpty(proxies)) {
            Proxy proxy = proxies.get(0);
//        Proxy proxy=new Proxy(Proxy.Type.HTTP,new DomainSocketAddress("http://10.99.105.119/hb2020.pac"));
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setProxy(proxy);
            restTemplate = new RestTemplate(requestFactory);
        }else {
            restTemplate=new RestTemplate();
        }
        for (BasePersonInfo basePersonInfo:basePersonInfos){
            JSONObject param=new JSONObject();
            param.put("userIDs",Arrays.asList(basePersonInfo.getUserGuid()));
            param.put("systemName","总署智慧值班系统");
            HttpHeaders head=new HttpHeaders();
            head.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity=new HttpEntity(param,head);
            try {
                log.info("通讯录电话地址"+systemConfig.getAddressPhoneUrl());
                log.info("通讯录电话参数"+param);
                JSONArray jsonObjectResult=restTemplate.postForObject(systemConfig.getAddressPhoneUrl(),httpEntity,JSONArray.class);
                log.info("通讯录电话返回"+jsonObjectResult);
                if (!CollectionUtils.isEmpty(jsonObjectResult)){
                    basePersonInfo.setPhoneLand(jsonObjectResult.getJSONObject(0).getString("telNo"));
                    basePersonInfo.setPhoneShort(jsonObjectResult.getJSONObject(0).getString("telNet"));
                }
            }catch (Exception e){
                log.error("获取通讯录数据失败",e);
            }
            try {
                String imgUrl=systemConfig.getAddressPhoneLongUrl()+"?userID="
                        +basePersonInfo.getUserGuid()+"&customsID="+basePersonInfo.getParentGuid()+"&systemName=总署智慧值班系统&viewUserID="
                        +systemConfig.getViewValues()+"&viewUserName="+systemConfig.getViewUserName()+"&viewUserIP="+systemConfig.getViewUserIp();
                log.info("通讯录长号地址"+imgUrl);
                String jsonObjectResult=restTemplate.getForObject(imgUrl+"&systemName=总署智慧值班系统",String.class);
                log.info("通讯录长号返回"+jsonObjectResult);
                if (jsonObjectResult!=null&&!"[]".equals(jsonObjectResult)){
                    String temp=JSONArray.parseArray(jsonObjectResult).getJSONObject(0).getString("telMob");
                    if (!StringUtils.isEmpty(temp)) {
                        basePersonInfo.setPhone(temp);
                    }
                }
            }catch (Exception e){
                log.error("获取通讯录长号失败",e);
            }
//            try {
//                String imgUrl=systemConfig.getAddressImgUrl()+"?userID="
//                        +basePersonInfo.getUserGuid()+"&customsID="+basePersonInfo.getParentGuid()+"&systemName=总署智慧值班系统";
////                log.info("通讯录头像地址"+imgUrl);
//                String jsonObjectResult=restTemplate.getForObject(imgUrl+"&systemName=总署智慧值班系统",String.class);
////                log.info("通讯录头像返回"+jsonObjectResult);
//                if (jsonObjectResult!=null){
//                    basePersonInfo.setFacePath(JSONObject.parseObject(jsonObjectResult).getString("userPhoto"));
//                }
//            }catch (Exception e){
//                log.error("获取通讯录头像失败",e);
//            }
            resultList.add(basePersonInfo);
        }
        return  resultList;
    }

/*
    private List<BasePersonInfo> getPersonAddressMsg(List<BasePersonInfo> basePersonInfos) throws URISyntaxException {
        if (CollectionUtils.isEmpty(basePersonInfos)){
            return basePersonInfos;
        }


        List<BasePersonInfo> resultList=new ArrayList<>();
//        List<BasePersonInfo> getInfos=new ArrayList<>();
//        int flag=0;
//        List<String> userIds=new ArrayList<>();
//        if (basePersonInfos.size()<=100){
//             userIds=basePersonInfos.stream().map(BasePersonInfo::getUserGuid).collect(Collectors.toList());
//
//        }
//        ProxySelector.setDefault(new MyProxySelector());
        ProxySelector proxySelector=new MyProxySelector();
        List<Proxy> proxies=proxySelector.select(new URI(systemConfig.getAddressPhoneUrl()));
        RestTemplate restTemplate;
        if (!CollectionUtils.isEmpty(proxies)) {
            Proxy proxy = proxies.get(0);
//        Proxy proxy=new Proxy(Proxy.Type.HTTP,new DomainSocketAddress("http://10.99.105.119/hb2020.pac"));
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setProxy(proxy);
            restTemplate = new RestTemplate(requestFactory);
        }else {
            restTemplate=new RestTemplate();
        }
        for (BasePersonInfo basePersonInfo:basePersonInfos){
            JSONObject param=new JSONObject();
            param.put("userIDs",Arrays.asList(basePersonInfo.getUserGuid()));
            param.put("systemName","总署智慧值班系统");
            HttpHeaders head=new HttpHeaders();
            head.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity=new HttpEntity(param,head);
            try {
                log.info("通讯录电话地址"+systemConfig.getAddressPhoneUrl());
                log.info("通讯录电话参数"+param);
                JSONArray jsonObjectResult=restTemplate.postForObject(systemConfig.getAddressPhoneUrl(),httpEntity,JSONArray.class);
                log.info("通讯录电话返回"+jsonObjectResult);
                if (!CollectionUtils.isEmpty(jsonObjectResult)){
                    basePersonInfo.setPhone(jsonObjectResult.getJSONObject(0).getString("telNo"));
                    basePersonInfo.setPhoneLand(jsonObjectResult.getJSONObject(0).getString("telNo2"));
                    basePersonInfo.setPhoneShort(jsonObjectResult.getJSONObject(0).getString("telNet"));
                }
            }catch (Exception e){
                log.error("获取通讯录数据失败",e);
            }

            try {
                String imgUrl=systemConfig.getAddressImgUrl()+"?userID="
                        +basePersonInfo.getUserGuid()+"&customsID="+basePersonInfo.getParentGuid()+"&systemName=总署智慧值班系统";
                log.info("通讯录头像地址"+imgUrl);
                String jsonObjectResult=restTemplate.getForObject(imgUrl+"&systemName=总署智慧值班系统",String.class);
                log.info("通讯录头像返回"+jsonObjectResult);
                if (jsonObjectResult!=null){
                    basePersonInfo.setFacePath(JSONObject.parseObject(jsonObjectResult).getString("userPhoto"));
                }
            }catch (Exception e){
                log.error("获取通讯录头像失败",e);
            }
            resultList.add(basePersonInfo);
        }
        return  resultList;
    }
*/

    private List<BaseDeptInfo> getDeptCustom(List<BaseDeptInfo> baseDeptInfos, List<ScreenDutyMaps> allCustomMap) {
        Map<String,String> customMap=allCustomMap.stream().collect(Collectors.toMap(ScreenDutyMaps::getCustomCode,ScreenDutyMaps::getCustomName,(customName1,customName2)->customName1));
        Map<String,BaseDeptInfo> baseDeptInfoMap=baseDeptInfos.stream().collect(Collectors.toMap(BaseDeptInfo::getId,i->i));
        List<BaseDeptInfo> result=new ArrayList<>();
        for (BaseDeptInfo baseDeptInfo:baseDeptInfos){
            log.info(JSON.toJSONString(baseDeptInfo));
            baseDeptInfo= doDeptCustom(baseDeptInfo,customMap,baseDeptInfoMap);
            if (baseDeptInfo.getCustomName()==null){
//                baseDeptInfo.setCustomName("海关总署");
                //改成读配置
                baseDeptInfo.setCustomName(systemConfig.getZsCustomName());
                ParamDictionary paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                        .eq(ParamDictionary::getParamModule, "ZBRY")
                        .eq(ParamDictionary::getParamCode, "JCBMID"), false);
                baseDeptInfo.setCustomId(paramDictionary.getParamName());
            }
            result.add(baseDeptInfo);
        }
        return result;
    }

    private BaseDeptInfo doDeptCustom(BaseDeptInfo baseDeptInfo, Map<String, String> customMap, Map<String, BaseDeptInfo> baseDeptInfoMap) {
        if (baseDeptInfo.getParentid() == null || baseDeptInfo.getParentid().equals(baseDeptInfo.getOrgGuid())) {
            return baseDeptInfo;
        }
        if (customMap.containsKey(baseDeptInfo.getId())) {
            baseDeptInfo.setCustomId(baseDeptInfo.getId());
            baseDeptInfo.setCustomName(customMap.get(baseDeptInfo.getId()));
            return baseDeptInfo;
        }
        if (customMap.containsKey(baseDeptInfo.getParentid())) {
            baseDeptInfo.setCustomId(baseDeptInfo.getParentid());
            baseDeptInfo.setCustomName(customMap.get(baseDeptInfo.getParentid()));
            return baseDeptInfo;
        }
        BaseDeptInfo father = baseDeptInfoMap.get(baseDeptInfo.getParentid());
        if (father == null) {
            return baseDeptInfo;
        }
        BaseDeptInfo custom = doDeptCustom(father, customMap, baseDeptInfoMap);
        baseDeptInfo.setCustomId(custom.getCustomId());
        baseDeptInfo.setCustomName(custom.getCustomName());
        return baseDeptInfo;
    }

    private boolean isCJDept(SsoDept ssoDept, List<String> cjDeptNames) {
        if (ssoDept!=null&&(cjDeptNames.contains(ssoDept.getDisplayName()))){
            return true;
        }
        return false;
    }

    private boolean notUseSSoDept(SsoDept ssoDept, List<String> notUseDeptNames) {
        //SELECT *  FROM base_dept_info WHERE PARENTid='0c037a4d-bf06-4107-b9b8-f73649c742e1' AND  del_flag=0 AND
        // ( dept_name IN ('关领导','总工程师','总检验师','数据分中心','后勤管理中心','缉私局','技术中心','保健中心','海关学会','整体智治建设专题小组') OR dept_name LIKE '%纪检%')
        if (ssoDept!=null&&(notUseDeptNames.contains(ssoDept.getAllPathName()))){
            return true;
        }
        return false;
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    @XxlJob("messageSend")
    public ReturnT<String> messageSend(String param) {
        try {
            log.info( "开始短信提醒任务" );
            LocalDateTime localDateTime = LocalDateTime.now();
            List<ParamSmsTemplate> templateList = paramSmsTemplateRepository.list(new LambdaQueryWrapper<ParamSmsTemplate>()
                    .eq(ParamSmsTemplate::getDelFlag, DeleteFlagEnum.NOT_DELETE.getValue())
                    .eq( ParamSmsTemplate::getIsSend , IsSendEnum.IS.getCode() )
            );

            for ( ParamSmsTemplate smsTemplate : templateList ) {
                // 发送短信的所有手机号
                List< String > phones = new ArrayList<>();

                if ( SmsEnum.DUTY.getCode().equals( smsTemplate.getSmsType() ) ) {
                    log.info( "开始发送值班提醒短信类型" );

                    // 查询短信模板对应海关当天的值班信息 分为总署和隶属两种情况
                    List< DutyScheduleInfo > dutyScheduleInfos = new ArrayList<>();
                    if ( systemConfig.getZsCustomId().equals( smsTemplate.getTemplateCode() ) ) {
                       dutyScheduleInfos = dutyScheduleInfoRepository.list( new LambdaQueryWrapper< DutyScheduleInfo >()
                                .in( DutyScheduleInfo::getCustomId , smsTemplate.getTemplateCode() )
                                .in( DutyScheduleInfo::getDutyType , "3" , "4" )
                                .le( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().plusMonths( 1 ) )
                                .ge( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().minusMonths( 1 ) )
//                                .eq( DutyScheduleInfo::getDutyTimesId , smsTemplate.getParamDutyId() )
                       );
                    }else {
                        dutyScheduleInfos = dutyScheduleInfoRepository.list( new LambdaQueryWrapper< DutyScheduleInfo >()
                                .in( DutyScheduleInfo::getCustomId , smsTemplate.getTemplateCode() )
                                .in( DutyScheduleInfo::getDUserjob , "科领导" , "科员" )
                                .eq( org.apache.commons.lang3.StringUtils.isNotBlank( smsTemplate.getParamDutyId() ) ,
                                        DutyScheduleInfo::getDutyTimesId , smsTemplate.getParamDutyId() )
                                .le( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().plusMonths( 1 ) )
                                .ge( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().minusMonths( 1 ) )
                                .eq( DutyScheduleInfo::getDutyTimesId , smsTemplate.getParamDutyId() )

                        );
                    }

                    // 遍历值班信息 根据 dStartDateTime 和 短信提前时间进行逻辑判断
                    for ( DutyScheduleInfo scheduleInfo : dutyScheduleInfos ) {
                        // 值班开始时间 往前推 提前时间的日期 (短信发送时间)
                        LocalTime sendTime = smsTemplate.getSSendTime();
                        LocalDateTime messageSendTime = scheduleInfo.getDDay().atTime(sendTime).minusDays(smsTemplate.getSSendBefore());
                        long minutes = Duration.between( messageSendTime , localDateTime ).toMinutes();
//                        long minutes = Duration.between( localDateTime , messageSendTime ).toMinutes();

                        if ( minutes > 0 && minutes <= systemConfig.getSmsSendMinutes() ) {
                            log.info("localDateTime："+localDateTime+"messageSendTime:"+messageSendTime+"minutes："+minutes+"关区："+smsTemplate.getTemplateName()+"排班提醒人员："+scheduleInfo.getDUsername());
                            phones.add( scheduleInfo.getDPhone() );
                        }
                    }
                }else if ( SmsEnum.SIGN_IN_EXCEPTION.getCode().equals( smsTemplate.getSmsType() ) || SmsEnum.SIGN_OUT_EXCEPTION.getCode().equals( smsTemplate.getSmsType() ) ){ // 签到签退没有总署
                    log.info( "开始发送签到签退异常短信类型" );
                    List< DutyScheduleInfo > dutyScheduleInfos = dutyScheduleInfoRepository.list( new LambdaQueryWrapper< DutyScheduleInfo >()
                            .in( DutyScheduleInfo::getCustomId , smsTemplate.getTemplateCode() )
                            .in( DutyScheduleInfo::getDUserjob , "科领导" , "科员" )
                            .le( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().plusDays( 2 ) )
                            .ge( DutyScheduleInfo::getDDay , localDateTime.toLocalDate().minusDays( 2 ) )
                    );

                    // 遍历当天值班信息 根据 dStartDateTime 和 超过时间进行逻辑判断
                    for ( DutyScheduleInfo scheduleInfo : dutyScheduleInfos ) {
                        // 值班开始时间 往前推 提前时间的日期 (短信发送时间)
                        LocalDateTime messageSendTime;
                        DutySignInfo signInfos;
                        if ( SmsEnum.SIGN_IN_EXCEPTION.getCode().equals( smsTemplate.getSmsType() ) ){
                            messageSendTime = scheduleInfo.getDStartDateTime();
                            signInfos = dutySignInfoRepository.getOne( new LambdaQueryWrapper< DutySignInfo >()
                                    .eq( DutySignInfo::getDId , scheduleInfo.getId() )
                                    .eq( DutySignInfo::getDSigninType , SignEnum.IS.getCode() ) , false );
                        }else {
                            messageSendTime = scheduleInfo.getDEndDateTime();
                            signInfos = dutySignInfoRepository.getOne( new LambdaQueryWrapper< DutySignInfo >()
                                    .eq( DutySignInfo::getDId , scheduleInfo.getId() )
                                    .eq( DutySignInfo::getDSignoutType , SignEnum.IS.getCode() ) , false );
                        }
//                        long minutes = Duration.between( localDateTime , messageSendTime ).toMinutes();
                        long minutes = Duration.between( messageSendTime , localDateTime ).toMinutes();
                        log.info("localDateTime："+localDateTime);
                        log.info("SmsType："+smsTemplate.getSmsType());
                        log.info( "messageSendTime："+messageSendTime);
                        log.info( "minutes："+minutes);
                        if ( minutes > smsTemplate.getSSendBefore() && minutes <= ( systemConfig.getSmsSendMinutes() + smsTemplate.getSSendBefore() ) ) {
                            if( ObjectUtils.isNotEmpty( signInfos ) ) {
                                continue;
                            }
                            log.info("满足条件=====localDateTime："+localDateTime);
                            log.info("满足条件=====SmsType："+smsTemplate.getSmsType());
                            log.info( "满足条件=====messageSendTime："+messageSendTime);
                            log.info( "满足条件=====minutes："+minutes);
                            // 短信提醒人员表 手机号添加到phones
                            // 是否提醒值班员
                            if ( smsTemplate.getIsDuty().equals( IsDutyEnum.IS.getCode() ) ) {
                                phones.add( scheduleInfo.getDPhone() );
                            }
                        }
                    }
                }else {
                    log.info( "未知短信类型" );
                    continue;
                }

                sendMessage( phones , smsTemplate.getRemark() );

            }



        } catch ( Exception e ) {
            log.error( "短信发送功能异常" , e );
        }
        return ReturnT.SUCCESS;
    }


    @XxlJob("getEmergencyPlan")
//    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> getEmergencyPlan(String param) {
        try {
            log.info("进行应急预案人员拉取");
            List<ScreenNotice> screenEmergencyPlans=screenNoticeRepository.list();
            if (CollectionUtils.isEmpty(screenEmergencyPlans)){
                doInitEmergency();
            }else {
                getTodayEmergency();
            }
        }catch (Exception e){
            log.error("进行应急预案人员拉取功能异常",e);
        }
        return ReturnT.SUCCESS;
    }

    @XxlJob("createSignForTempPerson")
//    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> createSignForTempPerson(String param) {
        try {
            log.info("createSignForTempPerson Start");
            List<DutyScheduleInfo> dutyScheduleInfos=dutyScheduleInfoRepository.list();
            for (DutyScheduleInfo dutyScheduleInfo:dutyScheduleInfos) {
                DutySignInfo info = dutySignInfoRepository.getOne(new LambdaQueryWrapper<DutySignInfo>()
                        .eq(DutySignInfo::getDId,dutyScheduleInfo.getId()),false);
                if (info==null) {
                    if (!org.apache.commons.lang.StringUtils.isEmpty(dutyScheduleInfo.getDUserno())) {
                        DutySignInfo dutySignInfo = new DutySignInfo();
                        dutySignInfo.setDId(dutyScheduleInfo.getId());
                        dutySignInfo.setCreateBy("sys");
                        dutySignInfo.setCreateTime(LocalDateTime.now());
                        dutySignInfo.setUpdateBy("sys");
                        dutySignInfo.setUpdateTime(LocalDateTime.now());
                        dutySignInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        dutySignInfoRepository.save(dutySignInfo);
                    }
                }
            }
        }catch (Exception e){
            log.error("createSignForTempPerson",e);
        }
        return ReturnT.SUCCESS;
    }

    @XxlJob("warnMapTask")
//    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> warnMapTask(String param) {
        try {
            //step1首先，我要所有的关区
            LocalDateTime now = LocalDateTime.now();
            List<ScreenDutyMaps> screenDutyMaps=screenDutyMapsRepository.list();
            log.info( "所有关区screenDutyMaps{} " , screenDutyMaps );
            List<ScreenDutyLog> screenDutyLogs=screenDutyLogRepository.list(new LambdaQueryWrapper<ScreenDutyLog>()
                    .ge(ScreenDutyLog::getCreateTime,now.toLocalDate().atStartOfDay())
                    .lt(ScreenDutyLog::getCreateTime,now.toLocalDate().atStartOfDay().plusDays(1l))
                );
            log.info( "screenDutyLogs{} " , screenDutyLogs );
            List<ScreenDutyMessage> screenDutyMessages=screenDutyMessageRepository.list(new LambdaQueryWrapper<ScreenDutyMessage>()
                    .ge(ScreenDutyMessage::getCreateTime,now.toLocalDate().atStartOfDay())
                    .lt(ScreenDutyMessage::getCreateTime,now.toLocalDate().atStartOfDay().plusDays(1l))
                    .isNotNull(ScreenDutyMessage::getOriginMsgId)
            );
            log.info( "screenDutyMessages{} " , screenDutyMessages );
            List<ScreenDutyMaps> yellowList=new ArrayList<>();
            List<ScreenDutyNoticeList> screenDutyNoticeLists=screenDutyNoticeListRepository.list(new LambdaQueryWrapper<ScreenDutyNoticeList>()
                    .le(ScreenDutyNoticeList::getStartTime,now)
                    .ge(ScreenDutyNoticeList::getEndTime,now));
            log.info( "screenDutyNoticeLists{} " , screenDutyNoticeLists );
            Map<String,JSONObject> cityMap=new HashMap<>();
            //step2为这些关区赋值值班人
            log.info( "开始为关区赋值值班人" );
            for (ScreenDutyMaps map:screenDutyMaps) {
                log.info( "map{}" , map  );
                DutyScheduleInfoTimeDTO todayDTO = getTimeDTOForDay(map.getCustomName(), now);
                log.info( "todayDTO{}" , todayDTO  );

                if (todayDTO != null) {
                    if (todayDTO.getKJInfo() != null) {
                        if (todayDTO.getKJInfo().getDUserno() != null) {
                            BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                                    .eq(BasePersonInfo::getUserno, todayDTO.getKJInfo().getDUserno()), false);
                            log.info( "科级值班员" , basePersonInfo );
                            if (basePersonInfo != null) {
                                if (todayDTO.getKJInfo().getDUsername() == null) {
                                    map.setDutyPersonName(basePersonInfo.getUsername());
                                } else {
                                    map.setDutyPersonName(todayDTO.getKJInfo().getDUsername());
                                }
                                if (todayDTO.getKJInfo().getFacePath() == null) {
                                    map.setDutyPersonImg(basePersonInfo.getFacePath());
                                } else {
                                    map.setDutyPersonImg(todayDTO.getKJInfo().getFacePath());
                                }
                                map.setDutyPersonNo(basePersonInfo.getUserno());
                                if (todayDTO.getKJInfo().getDPhone() == null) {
                                    map.setDutyPersonPhone(basePersonInfo.getPhone());
                                } else {
                                    map.setDutyPersonPhone(todayDTO.getKJInfo().getDPhone());
                                }
                                if (todayDTO.getKJInfo().getPhoneShort() == null) {
                                    map.setDutyPersonPhoneShort(basePersonInfo.getPhoneShort());
                                } else {
                                    map.setDutyPersonPhoneShort(todayDTO.getKJInfo().getPhoneShort());
                                }
                                map.setDutyPersonRank("值班员");
                                if (!StringUtils.isEmpty(systemConfig.getDoYellowCheck()) && "1".equals(systemConfig.getDoYellowCheck())) {
                                    if (todayDTO.getKJInfo().getDStartDateTime() != null) {
                                        if (todayDTO.getKJInfo().getDStartDateTime().compareTo(now) < 0
                                                && todayDTO.getKJInfo().getDEndDateTime().compareTo(now) > 0) {
                                            List<DutySignInfo> listin = dutySignInfoRepository.list(new LambdaQueryWrapper<DutySignInfo>()
                                                    .eq(DutySignInfo::getDId, todayDTO.getKJInfo().getId())
                                                    .eq(DutySignInfo::getDSigninType, "1"));
                                            log.info( "值班人员签到记录，listin{}" , listin);
                                            if (CollectionUtils.isEmpty(listin)) {
                                                map.setWarn(WarnTypeEunm.YELLOW.getValue());
                                                map.setWarnCont("值班人员未到岗");
                                                yellowList.add(map);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }else {
                        map.setDutyPersonName("");
                        map.setDutyPersonImg("");
                        map.setDutyPersonPhone("");
                        map.setDutyPersonPhoneShort("");
                        map.setDutyPersonNo("");
                    }
                    if (todayDTO.getManagerInfo() != null) {
                        if (todayDTO.getManagerInfo().getDUserno() != null) {
                            BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                                    .eq(BasePersonInfo::getUserno, todayDTO.getManagerInfo().getDUserno()));
                            log.info( "ManagerInfo" , basePersonInfo );

                            if (basePersonInfo!=null) {
                                if (todayDTO.getManagerInfo().getDUsername()==null) {
                                    map.setLeaderPersonName(basePersonInfo.getUsername());
                                }else {
                                    map.setLeaderPersonName(todayDTO.getManagerInfo().getDUsername());
                                }
                                if (todayDTO.getManagerInfo().getFacePath()==null) {
                                    map.setLeaderPersonImg(basePersonInfo.getFacePath());
                                }else {
                                    map.setLeaderPersonImg(todayDTO.getManagerInfo().getFacePath());
                                }
                                map.setLeaderPersonNo(basePersonInfo.getUserno());
                                if (todayDTO.getManagerInfo().getDPhone()==null) {
                                    map.setLeaderPersonPhone(basePersonInfo.getPhone());
                                }else {
                                    map.setLeaderPersonPhone(todayDTO.getManagerInfo().getDPhone());
                                }
                                if (todayDTO.getManagerInfo().getPhoneShort()==null) {
                                    map.setLeaderPersonPhoneShort(basePersonInfo.getPhoneShort());
                                }else {
                                    map.setLeaderPersonPhoneShort(todayDTO.getManagerInfo().getPhoneShort());
                                }
                                map.setLeaderPersonRank("带班领导");
                            }
                        }
                    }else {
                            map.setLeaderPersonName("");
                            map.setLeaderPersonImg("");
                            map.setLeaderPersonNo("");
                            map.setLeaderPersonPhone("");
                            map.setLeaderPersonPhoneShort("");
                    }
                    if (todayDTO.getCJInfo() != null) {
                        if (todayDTO.getCJInfo().getDUserno() != null) {
                            BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                                    .eq(BasePersonInfo::getUserno, todayDTO.getCJInfo().getDUserno()));
                            log.info( "CJInfo" , basePersonInfo );
                            if (basePersonInfo!=null) {
                                if (todayDTO.getCJInfo().getDUsername()==null) {
                                    map.setCjPersonName(basePersonInfo.getUsername());
                                }else {
                                    map.setCjPersonName(todayDTO.getCJInfo().getDUsername());
                                }
                                if (todayDTO.getCJInfo().getFacePath()==null) {
                                    map.setCjPersonImg(basePersonInfo.getFacePath());
                                }else {
                                    map.setCjPersonImg(todayDTO.getCJInfo().getFacePath());
                                }
                                map.setLeaderPersonNo(basePersonInfo.getUserno());
                                if (todayDTO.getCJInfo().getDPhone()==null) {
                                    map.setCjPersonPhone(basePersonInfo.getPhone());
                                }else {
                                    map.setCjPersonPhone(todayDTO.getCJInfo().getDPhone());
                                }
                                if (todayDTO.getCJInfo().getPhoneShort()==null) {
                                    map.setCjPersonPhoneShort(basePersonInfo.getPhoneShort());
                                }else {
                                    map.setCjPersonPhoneShort(todayDTO.getCJInfo().getPhoneShort());
                                }
                                map.setCjPersonRank("处领导");
                            }
                        }
                    }else {
                        map.setCjPersonName("");
                        map.setCjPersonImg("");
                        map.setCjPersonNo("");
                        map.setCjPersonPhone("");
                        map.setCjPersonPhoneShort("");
                    }
                    log.info( "map" , map );
                }
            }
                //其次，这些关区的红色情况----目前只有值班日志与值班预警，均取今天
                List<ScreenDutyMaps> redList = new ArrayList<>();
                for (ScreenDutyMaps map : screenDutyMaps) {
                    log.info( "ScreenDutyMaps红色{}" ,map );
                    Set<String> citySet = cityMap.keySet();
                    log.info( "citySet" , citySet);
                    if (!CollectionUtils.isEmpty(citySet)) {
                        for (String city : citySet) {
                            if (map.getCustomName().contains(city)) {
                                map.setWarn(WarnTypeEunm.RED.getValue());
                                map.setWarnCont(cityMap.get(city).getString("alarm_title").replaceAll("浙江省",""));
                                redList.add(map);
                            }
                        }
                    }
                    if (!CollectionUtils.isEmpty(screenDutyLogs)) {
                        List<ScreenDutyLog> myWorks = screenDutyLogs.stream()
                                .filter(i -> i.getCustomId() != null && i.getCustomId().equals(map.getCustomCode()) && WarnTypeEunm.RED.getValue().equals(i.getNoticeType())).collect(Collectors.toList());
                        log.info( "红色screenDutyLogs-myWorks" , myWorks);
                        if (!CollectionUtils.isEmpty(myWorks) && !redList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode())) {
                            map.setWarn(WarnTypeEunm.RED.getValue());
                            map.setWarnCont(myWorks.get(0).getMainBody());
                            redList.add(map);
                        }
                    }
                    if (!CollectionUtils.isEmpty(screenDutyMessages)) {
                        List<ScreenDutyMessage> myWorks = screenDutyMessages.stream()
                                .filter(i -> i.getCustomId() != null && i.getCustomId().equals(map.getCustomCode())).collect(Collectors.toList());
                        log.info( "红色screenDutyMessages-myWorks" , myWorks);
                        if (!CollectionUtils.isEmpty(myWorks) && !redList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode())) {
                            map.setWarn(WarnTypeEunm.RED.getValue());
                            map.setWarnCont(myWorks.get(0).getTitle());
                            redList.add(map);
                        }
                    }
                    if (!CollectionUtils.isEmpty(screenDutyNoticeLists)) {
                        List<ScreenDutyNoticeList> myWorks = screenDutyNoticeLists.stream()
                                .filter(i -> i.getCustomId() != null && i.getCustomId().contains(map.getCustomCode()) && "1".equals(i.getNoticeType())).collect(Collectors.toList());
                        log.info( "红色screenDutyNoticeLists-myWorks" , myWorks);
                        if (!CollectionUtils.isEmpty(myWorks) && !redList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode())) {
                            map.setWarn(WarnTypeEunm.RED.getValue());
                            map.setWarnCont(myWorks.get(0).getMainBody());
                            redList.add(map);
                        }
                    }
                }
                log.info( "redList" , redList );
//            List<>
                //剩下关区的黄色情况

                for (ScreenDutyMaps map : screenDutyMaps) {
                    log.info( "ScreenDutyMaps黄色{}" ,map );
                    //此处调用天气预警接口
                    if (!CollectionUtils.isEmpty(screenDutyLogs)) {
                        List<ScreenDutyLog> myWorks = screenDutyLogs.stream()
                                .filter(i -> i.getCustomId() != null && i.getCustomId().equals(map.getCustomCode()) && WarnTypeEunm.YELLOW.getValue().equals(i.getNoticeType())).collect(Collectors.toList());
                        log.info( "黄色screenDutyLogs-myWorks" , myWorks);
                        if (!CollectionUtils.isEmpty(myWorks) && !redList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode()) && !yellowList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode())) {
                            map.setWarn(WarnTypeEunm.YELLOW.getValue());
                            map.setWarnCont(myWorks.get(0).getMainBody());
                            yellowList.add(map);
                        }
                    }
                    if (!CollectionUtils.isEmpty(screenDutyNoticeLists)) {
                        List<ScreenDutyNoticeList> myWorks = screenDutyNoticeLists.stream()
                                .filter(i -> i.getCustomId() != null && i.getCustomId().contains(map.getCustomCode()) && "0".equals(i.getNoticeType())).collect(Collectors.toList());
                        log.info( "黄色screenDutyNoticeLists-myWorks" , myWorks);
                        if (!CollectionUtils.isEmpty(myWorks) && !redList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode()) && !yellowList.stream().map(ScreenDutyMaps::getCustomCode).collect(Collectors.toList())
                                .contains(map.getCustomCode())) {
                            map.setWarn(WarnTypeEunm.YELLOW.getValue());
                            map.setWarnCont(myWorks.get(0).getMainBody());
                            yellowList.add(map);
                        }
                    }
                }
                log.info( "yellowList" , yellowList );
                    //默认就是绿色，全部入库---更新
                    List<ScreenDutyMaps> greenList = screenDutyMaps.stream().filter(i -> !redList.stream().map(j -> j.getId())
                            .collect(Collectors.toList()).contains(i.getId()) && !yellowList.stream().map(j -> j.getId())
                            .collect(Collectors.toList()).contains(i.getId())).collect(Collectors.toList());
            log.info( "greenList" , greenList );
            for (ScreenDutyMaps map : greenList) {
                        map.setWarn("1");
                        map.setWarnCont("值班人员签到正常");
                    }

            screenDutyMapsRepository.updateBatchById(screenDutyMaps);

        }catch (Exception e){
            log.error("地图警报功能异常",e);
        }
        return ReturnT.SUCCESS;
    }




    @XxlJob("getScheduleInfo")
    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> getScheduleInfo(String param) {
        try {
//            List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
//                    .notLike(BaseDeptType::getSupervisorname, "\\")
//                    .notLike(BaseDeptType::getSupervisorname, "/")
//                    .isNotNull(BaseDeptType::getThirdId));
//            List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
            String CJDeptName=paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                    .eq(ParamDictionary::getParamCode,"ZSGQ"),false).getParamName();
            log.info("CJDeptName:"+CJDeptName);
            List<String> customs=Arrays.asList(CJDeptName.split(","));
//        List<DutyScheduleInfo> list = getDutyScheduleInfoList(yearAndMonth, type, userInfoDetailVO);
            List<BaseDeptInfo> baseDeptInfos=baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                    .in(BaseDeptInfo::getDeptName,customs));
            log.info("baseDeptInfos:"+baseDeptInfos);
            baseDeptInfos=baseDeptInfos.stream().filter(i->i.getDeptName()!=null) .filter(distinctByKey(i->i.getDeptName())).collect(Collectors.toList());
            log.info("过滤后baseDeptInfos:"+baseDeptInfos);
            List<ScreenSchedulePerson> list = new ArrayList<>();
            for (BaseDeptInfo baseDeptInfo : baseDeptInfos) {
                if (systemConfig.getOrgValues().equals(baseDeptInfo.getDeptName())){
                    List<DutyScheduleInfo> todays = dutyScheduleInfoRepository.list(
                            new LambdaQueryWrapper<DutyScheduleInfo>()
                                    .eq(DutyScheduleInfo::getCustomName, baseDeptInfo.getDeptName())
                                    .eq(DutyScheduleInfo::getDDay,LocalDate.now()));
                    List<ScreenSchedulePerson> screenSchedulePeople=todays.stream().map(i->{
                        ScreenSchedulePerson KJscreenSchedulePerson =new ScreenSchedulePerson();
                        BeanUtils.copyProperties(i,KJscreenSchedulePerson);
                        KJscreenSchedulePerson.setDelFlag("0");
                        KJscreenSchedulePerson.setCustomName(baseDeptInfo.getDeptName());
                        KJscreenSchedulePerson.setCustomId(baseDeptInfo.getId());
                        return KJscreenSchedulePerson;
                    }).collect(Collectors.toList());
                    list.addAll(screenSchedulePeople);
                    log.info(systemConfig.getOrgValues()+"相等:"+screenSchedulePeople);
                    continue;
                }
                LocalDateTime now = LocalDateTime.now();
                    LocalDateTime tomorrow = LocalDateTime.now().toLocalDate().plusDays(1l).atStartOfDay();
                    DutyScheduleInfoTimeDTO todayDTO = getTimeDTOForDay(baseDeptInfo.getDeptName(), now);
                    DutyScheduleInfoTimeDTO tomorrowDTO = getTimeDTOForDay(baseDeptInfo.getDeptName(), tomorrow);
                    String todayString = getStringByTimeDTO(todayDTO);
                    String tomorrowString = getStringByTimeDTO(tomorrowDTO);
                    todayDTO.setTomorrowPerson(tomorrowString);
                    todayDTO.setTodayPerson(todayString);
                log.info(systemConfig.getOrgValues()+"不相等:"+todayDTO);
                    if(todayDTO.getKJInfo()!=null){
                        ScreenSchedulePerson KJscreenSchedulePerson =new ScreenSchedulePerson();
                        BeanUtils.copyProperties(todayDTO.getKJInfo(),KJscreenSchedulePerson);
                        KJscreenSchedulePerson.setTomorrowPerson(todayDTO.getTomorrowPerson());
                        KJscreenSchedulePerson.setTodayPerson(todayDTO.getTodayPerson());
                        KJscreenSchedulePerson.setDelFlag("0");
                        KJscreenSchedulePerson.setCustomName(baseDeptInfo.getDeptName());
                        KJscreenSchedulePerson.setCustomId(baseDeptInfo.getId());
                        KJscreenSchedulePerson.setDutyType("7");
                        list.add(KJscreenSchedulePerson);
                    }
                    if(todayDTO.getCJInfo()!=null){
                        ScreenSchedulePerson CJJscreenSchedulePerson =new ScreenSchedulePerson();
                        BeanUtils.copyProperties(todayDTO.getCJInfo(),CJJscreenSchedulePerson);
                        CJJscreenSchedulePerson.setTomorrowPerson(todayDTO.getTomorrowPerson());
                        CJJscreenSchedulePerson.setTodayPerson(todayDTO.getTodayPerson());
                        CJJscreenSchedulePerson.setDelFlag("0");
                        CJJscreenSchedulePerson.setCustomName(baseDeptInfo.getDeptName());
                        CJJscreenSchedulePerson.setCustomId(baseDeptInfo.getId());
                        CJJscreenSchedulePerson.setDutyType("6");
                        list.add(CJJscreenSchedulePerson);
                    }
                    if(todayDTO.getManagerInfo()!=null) {
                        ScreenSchedulePerson GJscreenSchedulePerson = new ScreenSchedulePerson();
                        BeanUtils.copyProperties(todayDTO.getManagerInfo(), GJscreenSchedulePerson);
                        GJscreenSchedulePerson.setTomorrowPerson(todayDTO.getTomorrowPerson());
                        GJscreenSchedulePerson.setTodayPerson(todayDTO.getTodayPerson());
                        GJscreenSchedulePerson.setDelFlag("0");
                        GJscreenSchedulePerson.setCustomName(baseDeptInfo.getDeptName());
                        GJscreenSchedulePerson.setCustomId(baseDeptInfo.getId());
                        GJscreenSchedulePerson.setDutyType("5");
                        list.add(GJscreenSchedulePerson);
                    }
            }
            screenSchedulePersonRepository.remove(new LambdaQueryWrapper<>());
            list.forEach(i->{
                i.setId(null);
                if ("null".equals(i.getTodayPerson())){
                    i.setTodayPerson("");
                }
                if ("null".equals(i.getTomorrowPerson())){
                    i.setTomorrowPerson("");
                }
            });
            log.info("list:"+list);
            screenSchedulePersonRepository.saveBatch(list);
            screenSchedulePersonRepository.remoteNotUseData();
        }catch (Exception e){
            log.error("任务执行异常",e);
        }
        return ReturnT.SUCCESS;
    }

    private void getTodayEmergency() {
        List<Subjecta> subjectas = subjectaRepository.list(new LambdaQueryWrapper<Subjecta>()
                .like(Subjecta::getSubjecta,"值班")
                .ge(Subjecta::getReleaseDate,LocalDateTime
                        .of(LocalDate.now().minusDays(1),LocalTime.of(0,0)))
                .lt(Subjecta::getReleaseDate,LocalDateTime
                        .of(LocalDate.now(),LocalTime.of(0,0)))
        );
        List<ScreenNotice> screenEmergencyPlans = subjectas.stream().map(i -> {
            ScreenNotice screenEmergencyPlan = new ScreenNotice();
            screenEmergencyPlan.setCreatePerson(i.getDraftPersonName());
            screenEmergencyPlan.setStatus("0");
            screenEmergencyPlan.setSource("2");
            screenEmergencyPlan.setHbId(i.getZxwwId());
            screenEmergencyPlan.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenEmergencyPlan.setJumpUrl(systemConfig.getHbJumpUrl()+screenEmergencyPlan.getHbId());
//            screenEmergencyPlan.setSort(1l);
            screenEmergencyPlan.setTitle(i.getSubjecta());
            screenEmergencyPlan.setApplyTime(i.getReleaseDate());
            List<Content> contents = contentRepository.list(new LambdaQueryWrapper<Content>()
                    .eq(Content::getResourceId, i.getZxwwId()));
            if(!CollectionUtils.isEmpty(contents)){
                screenEmergencyPlan.setMainBody(contents.get(0).getHtml());
            }else {
                screenEmergencyPlan.setMainBody(i.getContent());
            }
            return screenEmergencyPlan;
        }).collect(Collectors.toList());
        screenNoticeRepository.saveBatch(screenEmergencyPlans);
    }

    private void doInitEmergency() {
        List<Subjecta> subjectas = subjectaRepository.list(new LambdaQueryWrapper<Subjecta>()
                .like(Subjecta::getSubjecta,"值班")
        );
        List<ScreenNotice> screenEmergencyPlans = subjectas.stream().map(i -> {
            ScreenNotice screenEmergencyPlan = new ScreenNotice();
            screenEmergencyPlan.setCreatePerson(i.getDraftPersonName());
            screenEmergencyPlan.setStatus("0");
            screenEmergencyPlan.setSource("2");
            screenEmergencyPlan.setYear(i.getReleaseDate().getYear());
//            screenEmergencyPlan.setSort(1l);
            screenEmergencyPlan.setTitle(i.getSubjecta());
            screenEmergencyPlan.setHbId(i.getZxwwId());
            screenEmergencyPlan.setJumpUrl(systemConfig.getHbJumpUrl()+screenEmergencyPlan.getHbId());
            screenEmergencyPlan.setApplyTime(i.getReleaseDate());
            screenEmergencyPlan.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            List<Content> contents = contentRepository.list(new LambdaQueryWrapper<Content>()
                    .eq(Content::getResourceId, i.getZxwwId()));
            if(!CollectionUtils.isEmpty(contents)){
                screenEmergencyPlan.setMainBody(contents.get(0).getHtml());
            }else {
                screenEmergencyPlan.setMainBody(i.getContent());
            }
            return screenEmergencyPlan;
        }).collect(Collectors.toList());
        screenNoticeRepository.saveBatch(screenEmergencyPlans);
    }

    private void sendMessage(List<String> phones, String warnWord) {
        for (String phone : phones) {
            messageSendUtil.sendMessage(phone, warnWord);
        }
    }
    private BaseDeptInfo  getQTParent(BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> baseDeptInfoslist,ParamSmsTemplate paramSmsTemplate) {
        if (paramSmsTemplate.getTemplateName().equals(baseDeptInfo.getDeptName())){
            return null;
        }
        Map<String,BaseDeptInfo> baseDeptInfoMap=baseDeptInfoslist.stream().collect(Collectors.toMap(i->i.getId(),i->i));
        BaseDeptInfo father=baseDeptInfoMap.get(baseDeptInfo.getParentid());
        if (paramSmsTemplate.getTemplateName().equals(father.getDeptName())){
            return baseDeptInfo;
        }
        return getQTParent(father,baseDeptInfoslist,paramSmsTemplate);
    }
    private BaseDeptInfo  getParent(BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> baseDeptInfoslist) {
        if (systemConfig.getZsCustomName().equals(baseDeptInfo.getDeptName())){
            return null;
        }
        Map<String,BaseDeptInfo> baseDeptInfoMap=baseDeptInfoslist.stream().collect(Collectors.toMap(i->i.getId(),i->i));
        BaseDeptInfo father=baseDeptInfoMap.get(baseDeptInfo.getParentid());
        if (systemConfig.getZsCustomName().equals(father.getDeptName())){
            return baseDeptInfo;
        }
        return getParent(father,baseDeptInfoslist);
    }
    private BaseDeptInfo  getQJParent(BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> baseDeptInfoslist) {
        if ("钱江海关".equals(baseDeptInfo.getDeptName())){
            return null;
        }
        Map<String,BaseDeptInfo> baseDeptInfoMap=baseDeptInfoslist.stream().collect(Collectors.toMap(i->i.getId(),i->i));
        BaseDeptInfo father=baseDeptInfoMap.get(baseDeptInfo.getParentid());
        if ("钱江海关".equals(father.getDeptName())){
            return baseDeptInfo;
        }
        return getQJParent(father,baseDeptInfoslist);
    }
    private void  getChild(BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> childrens,  List<BaseDeptInfo> deptInfos) {
        List<BaseDeptInfo> myChildren=deptInfos.stream().filter(i->i.getParentid()!=null&&i.getParentid().equals(baseDeptInfo.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(myChildren)){
            childrens.addAll(myChildren);
            for (BaseDeptInfo child:myChildren){
                getChild(child,childrens,deptInfos);
            }
        }else {
            return ;
        }
    }
    private String getStringByTimeDTO(DutyScheduleInfoTimeDTO todayDTO) {
        String todayString="";
        if (todayDTO==null){
            return "";
        }
        if (todayDTO.getKJInfo()!=null){
            switch (todayDTO.getKJInfo().getSType()) {
                case "1":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    return todayString;
                case "2":
                case "3":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    break;
                default:return "";
            }
        }
        if (todayDTO.getCJInfo()!=null && !StringUtils.isEmpty(todayDTO.getCJInfo().getSType())){
            switch (todayDTO.getCJInfo().getSType()) {
                case "1":
                    return "";
                case "2":
                case "3":
                    if (org.apache.commons.lang.StringUtils.isEmpty(todayString)) {
                        if(todayDTO.getKJInfo()!=null){
                            todayString += todayDTO.getKJInfo().getDUsername();
                        }
                    }else  {
                        if(todayDTO.getKJInfo()!=null){
                            todayString =todayString+"、"+ todayDTO.getKJInfo().getDUsername();
                        }
                    }
                    break;
                default:return "";
            }
        }
        return todayString;
    }

    private DutyScheduleInfoTimeDTO getTimeDTOForDay(String customnName,LocalDateTime time){
        log.info( "getTimeDTOForDay方法开始,参数1{}，参数二{}" , customnName , time );
        BaseDeptInfo custom = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptName, customnName),false);
        LocalDateTime now = time;
        LocalDate today = time.toLocalDate();
        List<DutyScheduleInfo> dutyScheduleInfos = dutyScheduleInfoRepository.list(new LambdaQueryWrapper<DutyScheduleInfo>()
                .eq(DutyScheduleInfo::getCustomName, customnName)
                .lt(DutyScheduleInfo::getDStartDateTime,time)
                .ge(DutyScheduleInfo::getDEndDateTime,time)
                .orderByDesc(DutyScheduleInfo::getDStartDateTime)
        );
        log.info( "dutyScheduleInfos{}" , dutyScheduleInfos );
        if (CollectionUtils.isEmpty(dutyScheduleInfos)){
            dutyScheduleInfos = dutyScheduleInfoRepository.list(new LambdaQueryWrapper<DutyScheduleInfo>()
                            .eq(DutyScheduleInfo::getCustomName, customnName)
                            .eq(DutyScheduleInfo::getDDay, today)
                            .orderByDesc(DutyScheduleInfo::getDStartDateTime)
            );
            log.info( "dutyScheduleInfos为空,进if判断再查询{}" , dutyScheduleInfos );
        }
        DutyScheduleInfoTimeDTO result = new DutyScheduleInfoTimeDTO();
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            log.info( "dutyScheduleInfos为空" );
        } else {
            log.info( "dutyScheduleInfos不为空" );
            DutyScheduleInfo current = new DutyScheduleInfo();
                            List< DutyScheduleInfo > temp = dutyScheduleInfos.stream()
                                    .filter( i -> i.getDStartDateTime().compareTo( now ) < 0
                                            && i.getDEndDateTime().compareTo( now ) > 0 ).collect( Collectors.toList() );
                            if ( ! CollectionUtils.isEmpty( temp ) ) {
                                current = temp.get( 0 );
                            }
                            if ( current.getId() == null ) {
                                current = dutyScheduleInfos.get( 0 );
                            }

                     temp = dutyScheduleInfos.stream().filter(i -> i.getDStartDateTime().compareTo(now)<0 &&i.getDEndDateTime().compareTo(now)>0).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(temp)){
                        result.setKJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"科领导".equals(i.getDUserjob())||"科员".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"处领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setManagerInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"关领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    }else {
                        temp = dutyScheduleInfos;
                        result.setKJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"科领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"处领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setManagerInfo(temp.stream().map(i->{
                            DutyScheduleInfoTimeDetailDTO tempDTO= new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i,tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i->"关领导".equals(i.getDUserjob())).max((a,b)->a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    }
                    return result;
        }
        return result;
    }
    private String getDupostByH4a(String rankCode) {
        String result = "";
        if (rankCode==null){
            return result;
        }
        switch (rankCode) {
            case "05":
                result = "厅局级正职";
                break;
            case "06":
                result = "厅局级副职";
                break;
            case "07":
                result = "处级人员";
                break;
            case "08":
                result = "处级人员";
                break;
            case "09":
                result = "科长级人员";
                break;
            case "10":
                result = "科长级人员";
                break;
            case "11":
                result = "科员";
                break;
            case "99":
                result = "无行政级别";
                break;
            default:
                return "其他";
        }
        return result;
    }


    private String getPathPath(DutyScheduleInfo current) {
        if (current==null){
            return "";
        }
        BasePersonInfo basePersonInfo=basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                .eq(BasePersonInfo::getUserno,current.getDUserno()),false);
        if (basePersonInfo==null){
            return "";
        }
        return basePersonInfo.getFacePath();

    }

    @XxlJob( "getGroupInfo" )
    @Transactional(rollbackFor = Exception.class)
    public ReturnT< String > getGroupInfo( String param ) {
        try {
            log.info( "开始进行群组拉取任务" );
            List< ScreenDutyMaps > dutyMaps = screenDutyMapsRepository.list();

            // 添加总署
            String pathName = systemConfig.getZsPathName() ;
            if ( StringUtils.isEmpty( systemConfig.getZsPathName() ) ) {
                pathName = "中国海关" + "\\" + "拱北海关\\拱北值班室";
            }
            ScreenDutyMaps screenDutyMaps = new ScreenDutyMaps();
            screenDutyMaps.setCustomCode( systemConfig.getZsCustomId() );
            screenDutyMaps.setPathName( pathName );
            dutyMaps.add( screenDutyMaps );


            // H4A群组列表
            List< BaseGroupInfo > baseGroupInfos = new ArrayList<>();

            // 拉取
            for ( ScreenDutyMaps dutyMap : dutyMaps ) {
                OguBeanReaderHelper helperdept = new OguBeanReaderHelper();
                String orgValue = dutyMap.getPathName();
                if ( StringUtils.isEmpty( orgValue ) ) {
                    orgValue = "中国海关" + "\\" +dutyMap.getCustomName() + "\\" + "办公室（党委办公室）\\总值班室";
                }
                OrganizationChildren[] ogus = helperdept.getBeanOrganizationChildren( systemConfig.getViewValues() ,
                        ViewCategory.ViewCode , orgValue , OrganizationCategory.ORG_ALL_PATH_NAME , ListObjectCategories.Groups , ObjectStatusCategories.All , 0 , "05,06,07,08,99" , "" , "" , 0 , "ORG_GUID,PARENT_GUID,ALL_PATH_NAME,GLOBAL_SORT,DISPLAY_NAME,CUSTOMS_CODE,ORG_CLASS,ORG_TYPE," + "RANK_CODE,RANK_TYPE,SIDELINE,STATUS" );

                // h4a查询群组信息
                if ( ogus != null && ogus.length > 0 ) {
                    for ( int i = 0; i < ogus.length; i++ ) {
                        OrganizationChildren organizations = ogus[ i ];
                        // 过滤前面为值班_
                        if ( organizations.getDisplay_name().startsWith( "值班_" ) && !"3".equals( organizations.getStatus() )) {
                            BaseGroupInfo baseGroupInfo = new BaseGroupInfo();
                            baseGroupInfo.setCustomId( dutyMap.getCustomCode() );
                            baseGroupInfo.setGroupName( organizations.getDisplay_name() );
                            baseGroupInfo.setAllPathName( organizations.getAll_path_name() );
                            baseGroupInfo.setGroupGuid( organizations.getGroup_guid() );
                            baseGroupInfo.setDelFlag( "0" );
                            baseGroupInfo.setCreateBy( "sys" );
                            baseGroupInfo.setUpdateBy( "sys" );
                            baseGroupInfo.setSort( organizations.getGlobal_sort() );
                            baseGroupInfo.setCreateTime( LocalDateTime.now() );
                            baseGroupInfo.setUpdateTime( LocalDateTime.now() );
                            log.info( baseGroupInfo + "" );
                            baseGroupInfos.add( baseGroupInfo );
                        }
                    }
                }
            }
            baseGroupInfoRepository.remove( new LambdaQueryWrapper<>() );
            baseGroupInfoRepository.saveBatch( baseGroupInfos );

            // 根据群组拉人
            List< BaseGroupUserRelation > baseGroupUserRelations = new ArrayList<>();


            for ( BaseGroupInfo baseGroupInfo : baseGroupInfos ) {
                // 获取
                OguBeanReaderHelper helper = new OguBeanReaderHelper();
                UsersInGroups[] base_views = helper.getBeanUsersInGroups(systemConfig.getViewValues(), ViewCategory.ViewCode,baseGroupInfo.getAllPathName(), GroupCategory.GROUP_ALL_PATH_NAME,   "05,06,07,08,99",  ObjectStatusCategories.All, "PARENT_GUID,USER_GUID,DEPT_GUID,DISPLAY_NAME,PERSON_ID,GLOBAL_SORT,STATUS,ALL_PATH_NAME,RANK_CODE,RANK_NAME,SIDELINE");
                // 保存
                if ( base_views != null && base_views.length > 0 ) {
                    for ( int i = 0; i < base_views.length; i++ ) {
                        UsersInGroups organizationChildren = base_views[ i ];
                        BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno,organizationChildren.getPerson_id()),false);
                        if ( ObjectUtils.isEmpty( basePersonInfo ) ) {
                            continue;
                        }
                        BaseGroupUserRelation baseGroupUserRelation = new BaseGroupUserRelation();
                        baseGroupUserRelation.setGroupId( baseGroupInfo.getGroupGuid() );
                        baseGroupUserRelation.setUserId( basePersonInfo.getUserno() );
                        baseGroupUserRelation.setDelFlag( "0" );
                        baseGroupUserRelation.setCreateBy( "sys" );
                        baseGroupUserRelation.setUpdateBy( "sys" );
                        baseGroupUserRelation.setCreateTime( LocalDateTime.now() );
                        baseGroupUserRelation.setUpdateTime( LocalDateTime.now() );
                        baseGroupUserRelations.add( baseGroupUserRelation );
                    }
                }
            }

            baseGroupUserRelationRepository.remove( new LambdaQueryWrapper<>() );
            baseGroupUserRelationRepository.saveBatch( baseGroupUserRelations );

            // 删除掉delFlag为1的数据
            baseGroupInfoRepository.remoteNotUseData();
            baseGroupUserRelationRepository.remoteNotUseData();

        } catch ( Exception e ) {
            log.info( "拉取群组任务出现异常" , e );
        }
        log.info( "群组拉取任务结束" );

        return ReturnT.SUCCESS;
    }
}